package camid.distribution.lifecycle;

import camid.distribution.activeobject.ObjectRegistry;
import camid.distribution.activeobject.ObjectScheduler;
import camid.distribution.events.FutureNotificator;

public class StaticLifecycleManager extends AbstractLifecycleManager{

	private ObjectRegistry registry;
	
	public StaticLifecycleManager(ObjectRegistry objectRegistry)
	{
		super(objectRegistry);
		this.registry = objectRegistry;
	}

	public StaticLifecycleManager(ObjectRegistry objectRegistry,
			FutureNotificator futureNotificator) 
	{
		super(objectRegistry, futureNotificator);
		this.registry = objectRegistry;
	}

	public ObjectScheduler newObject(String objectId, Class<?> entityClass, 
			DefaultEntityFactory defaultObjectBuilder) throws InstantiationException, IllegalAccessException 
	{
		Object entity = defaultObjectBuilder.newEntity(entityClass);
		ObjectScheduler scheduler = new ObjectScheduler(objectId, entity);
		this.registry.add(scheduler);
		notifyObjectCreation(objectId, entityClass);
		return scheduler;
	}

	public ObjectScheduler getObject(String objectId) {
		ObjectScheduler scheduler = this.registry.get(objectId);
		return scheduler;
	}

	public ObjectScheduler destroyObject(String objectId) 
	{
		ObjectScheduler scheduler = this.registry.remove(objectId);
		this.notifyObjectDestruction(objectId);
		return scheduler;
	}

	public boolean hasObject(String objectId) {
		boolean hasObject = this.registry.contains(objectId);
		return hasObject;
	}

	@Override
	public ObjectScheduler insertObject(String objectId, Object entity)
	{
		ObjectScheduler scheduler = null;
		if(this.registry.contains(objectId))
		{
			scheduler = this.registry.remove(objectId);
		}
		else
		{
			scheduler = new ObjectScheduler(objectId, entity);
			this.registry.add(scheduler);
		}
		super.notifyObjectCreation(objectId, entity.getClass());
		return scheduler;
	}
	

}
